<?php
/*
	本插件：$this->model('taobaocsv')->方法名();
	其他地方调用：model('jy_weishopniu/taobaocsv')->方法名();
*/
namespace jy_weishopniu;
defined('BY_JYA') or exit('error');
class taobaocsv extends \plugin{
	/**
     * 淘宝csv采集
     */
	public function save_taobaocsv_goods($item = array(), $merchid = 0)
	{
		$params=array('uniacid'=>$_SESSION['uniacid'],'catch_source' => 'taobaocsv');
		$data = array(
			'uniacid' => $_SESSION['uniacid'],
			'param'=>ijson_encode($item['params']),
			'title' => $item['title'],
			'image' => $item['image'],
			'video' => $item['video'],
			'subtitle' => $item['subTitle'],
			'merchid' => $merchid,
			'total' => $item['total']?:18,
			'price' => $item['marketprice'],
			'minprice' => $item['marketprice'],
			'maxprice' => $item['marketprice'],
			'costprice' => $item['productPrice'],
			'pcate' => $item['pcate'],
			'ccate' => $item['ccate'],
			'tcate' => $item['tcate'],
			'salenum' => $item['sales'],
			'createtime' => time(),
			'updatetime' => time(),
			'isoption' => (0 < count($item['options']) ? 1 : 0),
			'status' => 0,
			'buylevels' => '',
			'showlevels' => '',
			'buygroups' => '',
			'showgroups' => '',
			'storeids' => '',
			'goodssn' => $item['goodssn'],
			'share_keywords' => $item['share_keywords'],
		);
		if (empty($item['merchid'])) {
			//$data['discounts'] = '{"type":"0","default":"","default_pay":""}';
		}

		if (!(empty($merchid))) {
			$data['nochecked'] = 1;
		}
		$thumb_url = array();
		$pics = $item['pics'];
		$piclen = count($pics);
		/*if (0 < $piclen) {
			$data['image'] = cfc('files')->source_save($pics[0],'image','jpg','商品单图','',0);
			if (1 < $piclen) {
				$i = 1;
				while ($i < $piclen) {
					$img = cfc('files')->source_save($pics[$i],'image','jpg','商品单图','',0);
					$thumb_url[] = $img;
					++$i;
				}
			}
		}*/
		$data['image'] =$pics[0];
		$data['images'] = ijson_encode($pics);
		pdo_insert('jy_weishop_goods', $data);
		$goodsid = pdo_insertid();
		$params['goodsid']=$goodsid;
		pdo_insert('jy_weishopniu_catch', $params);
		$content = $item['content'];
		$isupimg=$this->session('isupimg');
		if($isupimg){
			preg_match_all('/<img.*?src=[\\\\\'| \\"](.*?(?:[\\.gif|\\.jpg]?))[\\\\\'|\\"].*?[\\/]?>/', $content, $imgs);

			if (isset($imgs[1])) {
				foreach ($imgs[1] as $img) {
					$catchimg = $img;

					if (substr($catchimg, 0, 2) == '//') {
						$img = 'http://' . substr($img, 2);
					}

					$im = array('catchimg' => $catchimg, 'system' => cfc('files')->source_save($img,'image','','','',0));
					$images[] = $im;
				}
			}
		}
		$html = $content;

		if (isset($images)) {
			foreach ($images as $img) {
				if (!empty($img['system'])) {
					$html = str_replace($img['catchimg'], $img['system'], $html);
				}
			}
		}

		$html = $this->model('model')->html_to_images($html);

		if (isset($images[0])) {
			$d['thumb_url'] = serialize($images[0]);
			$d['thumb'] = $images[0]['catchimg'];
		}

		$d['content'] = $html;
		pdo_update('jy_weishop_goods', $d, array('id' => $goodsid));
		return array('result' => '1', 'goodsid' => $goodsid);
	}
	public function get_zip_originalsize($filename, $path)
	{
		if (!file_exists($filename)) {
			exit('文件 ' . $filename . ' 不存在！');
		}

		$filename = iconv('utf-8', 'gb2312', $filename);
		$path = iconv('utf-8', 'gb2312', $path);
		$resource = zip_open($filename);
		$i = 1;

		while ($dir_resource = zip_read($resource)) {
			if (zip_entry_open($resource, $dir_resource)) {
				$imagename=zip_entry_name($dir_resource);
				if(strrpos($imagename, '/')){
					$imagename = strrchr($imagename, '/');
				}
				$file_name = $path .$imagename;
				$file_path = substr($file_name, 0, strrpos($file_name, '/'));

				if (!is_dir($file_path)) {
					mkdir($file_path, 511, true);
				}

				if (!is_dir($file_name)) {
					$file_size = zip_entry_filesize($dir_resource);

					if ($file_size < 1024 * 1024 * 10) {
						$file_content = zip_entry_read($dir_resource, $file_size);
						$ext = strrchr($file_name, '.');

						if ($ext == '.png') {
							file_put_contents($file_name, $file_content);
						}else{
							if ($ext == '.tbi') {
								$file_name = substr($file_name, 0, strlen($file_name) - 4);
								file_put_contents($file_name . '.png', $file_content);
							}
						}
					}
				}

				zip_entry_close($dir_resource);
			}
		}
		cfc('files')->source_del($filename);
		zip_close($resource);
	}
	public function get_taobaocsvitems($rows,$zip='')
	{
			$num = count($rows);
			$i = 0;
			$colsIndex = array();
			foreach ($rows[1] as $cols => $col) {
				if ($col == 'title') {
					$colsIndex['title'] = $i;
				}

				if ($col == 'sku_barcode') {
					$colsIndex['sku_barcode'] = $i;
				}

				if ($col == 'price') {
					$colsIndex['price'] = $i;
				}

				if ($col == 'num') {
					$colsIndex['num'] = $i;
				}

				if ($col == 'description') {
					$colsIndex['description'] = $i;
				}

				if ($col == 'skuProps') {
					$colsIndex['skuProps'] = $i;
				}

				if ($col == 'picture') {
					$colsIndex['picture'] = $i;
				}

				if ($col == 'propAlias') {
					$colsIndex['propAlias'] = $i;
				}

				++$i;
			}
			$rows = array_slice($rows, 3, count($rows) - 3);
			$items = array();
			if($zip){
				$this->get_zip_originalsize($zip, ROOT_AT.'oss/' . $_SESSION['uniacid'] . '/images/' . date('Y') . '/' . date('m') . '/taobao/');
			}
			$num = 0;
			foreach ($rows as $rownu => $col) {
				$item = array();
				$item['title'] = $col[$colsIndex['title']];
				$item['marketprice'] = $col[$colsIndex['price']];
				$item['total'] = $col[$colsIndex['num']];
				$item['content'] = $col[$colsIndex['description']];
				$item['goodssn'] = $col[$colsIndex['sku_barcode']];
				$item['total'] = $col[$colsIndex['num']];
				$item['video'] = $col[$colsIndex['video']];
				$picContents = $col[$colsIndex['picture']];
				$allpics = explode(':|;', $picContents);
				$pics = array();
				$optionpics = array();
				//print_r($allpics);exit;
				foreach ($allpics as $imgurl) {
					if (empty($imgurl)) {
						continue;
					}
					$picDetail = explode(':', $imgurl);
					$imgurl = 'oss/' . $_SESSION['uniacid'] . '/images/' . date('Y') . '/' . date('m') . '/taobao/' . $picDetail[0] . '.png';
					if ($picDetail[1] == 1) {
						$pics[] = $imgurl;
					}
					if ($picDetail[1] == 2) {
						$optionpics[$picDetail[0]] = $imgurl;
					}
				}
				$item['pics'] = $pics;
				$item['image'] = $pics[0];
				$items[] = $item;
				++$num;
			}
			if(!$items[0]['title']){
				exi('上传文件失败：文件格式错误或文件内容为空！','error');
			}
			$items=ijson_encode($items);
			cache_write('taobaocsv'.$_SESSION['uid'],$items,'jy_weishopniu');
	}
	public function tb_str_getcsv($string, $delimiter=',', $enclosure='"') {
		$fp = fopen('php://temp/', 'r+');
		fputs($fp, $string);
		rewind($fp);
		while($t = fgetcsv($fp, strlen($string), $delimiter, $enclosure)) {
			$r[] = $t;
		}
		if(count($r) ==1) return current($r);
		return $r;
	}
}
?>